import sys
import os
import queue
from Module.xRayDetection.xray.logs import Logger
from universal.root_path import dir_root
import time
from Module.xRayDetection.ftp_function import *
from Module.xRayDetection.xray.xray import run
import re
from mylibs.zoomWidget import ZoomWidget
from PyQt5.QtGui import QIcon,QPixmap,QCursor
from PyQt5.QtWidgets import *

class TreeViewDemo(QTreeView):
    def __init__(self, parent=None):
        super(TreeViewDemo, self).__init__(parent)

        # window系统提供的模式
        path = ''
        self.model = QFileSystemModel()
        self.model.setRootPath(path)

        # 为控件添加模式。
        self.setModel(self.model)
        self.setRootIndex(self.model.index(path))  # 只显示设置的那个文件路径。
        self.setWindowTitle("QTreeView例子")
        self.resize(640, 480)
        self.canvas = None
        self.Path_Current = None
        self.main_detect = queue.Queue()
        self.main_detect.queue.clear()
        self.message = None
        self.device_combox = None
        self.tabel_view = None
        self.LocalDetectSaveContaniner = None
        self.ModelSaveContaniner = None
        self.select_line = None
        self.w1 = 1
        self.h1 = 1
        self.zoomWidget = ZoomWidget()

        self.clicked.connect(self.OneClicked)
        # 定义treewidget中item右键界面



    def OneClicked(self,Qmodelidx):
        Select_ = self.model.filePath(Qmodelidx)
        self.Path_Current.setText(Select_)

        # self.loca_tree__.device_combox = self.combox  # 设备控件传到local-Tree界面
        # self.loca_tree__.tabel_view = self.detect_tableWidget  # 表格控件传到Tree界面
        # self.loca_tree__.LocalDetectSaveContaniner = self.SavePath_
        # self.loca_tree__.ModelSaveContaniner = self.ModelPath_
        # self.loca_tree__.select_line = self.select_line

    #
    # def DetectFunction(self):
    #     root = "xRayDetection/linshi_local"
    #     logger = Logger(os.path.join(root, 'logs'))
    #     self.main_detect.queue.clear()
    #     sub_detect = queue.Queue()
    #
    #     DeviceAll = self.device_combox.currentText()  #选择设备
    #     if "c" in DeviceAll or 'C' in DeviceAll:
    #         device = 'cpu'
    #     else:
    #         device_list = re.findall(r"\d+\.?\d*", DeviceAll)
    #         device = str(",".join(device_list))
    #
    #     fold_thres = self.tabel_view.item(4, 1).text()
    #     cls_thres = self.tabel_view.item(5, 1).text()
    #     roi_thres = self.tabel_view.item(6, 1).text()
    #     LocalDetectSaveDir = self.LocalDetectSaveContaniner.text()#
    #     ModelSaveDir= self.ModelSaveContaniner.text()
    #     line = self.select_line.currentText()
    #
    #     cfg = {
    #         'logger': logger,
    #         'line': line,
    #
    #         'fold_thres': fold_thres,
    #         'cls_thres': cls_thres,
    #         'roi_thres': roi_thres,
    #         'device': device,
    #
    #         'save_dir': LocalDetectSaveDir,
    #         'local_model_dir': ModelSaveDir,
    #         'remote_dir': self.Select_,
    #         # 'remote_model_dir': '/platform/models',
    #         'upload_dir': '',             #必须传空，否则会上传至FTP
    #         'loop': 1,
    #         'main_queue':self.main_detect,
    #         'sub_queue':sub_detect,
    #         'root': dir_root(),
    #     }
    #
    #     self.DetectThread = threading.Thread(target=run,args=(cfg,))
    #     self.DetectThread.daemon = True
    #     self.DetectThread.start()
    #
    #     self.StatusThread = threading.Thread(target=self.DownloadStatus_detect, args=(self.main_detect, sub_detect))
    #     self.StatusThread.daemon = True
    #     self.StatusThread.start()
    #
    # def DownloadStatus_detect(self, main=None, sub=None):
    #     while True:
    #         time.sleep(0.1)
    #         try:
    #             flags = main.get(block=False)
    #         except:
    #             flags = {}
    #         if flags.get('stop', False):
    #             main.put({'stop': True})
    #             break
    #         try:
    #             result = sub.get(block=False)
    #             if result['idx'] == -1:
    #                 TextBrowserNews(self.message, news='路径下没有文件')
    #                 main.put({'stop': True})
    #                 break
    #             if result['idx'] == result['total']:
    #                 connect_ = result['msg']
    #                 TextBrowserNews(self.message, news=connect_)
    #                 main.put({'stop': True})
    #                 break
    #             if int(result['idx']) == 0:
    #                 self.message.append(result['path'])
    #             else:
    #                 connect_ = "第%s/%s ——>%s" % (result['idx'], result['total'], result['msg'])
    #                 TextBrowserNews(self.message, news=connect_)
    #                 Img = self.drawDetectBox(result['im'], result['det'])
    #                 Img = cvimg_to_qtimg(Img)
    #                 self.loadImg(Img)
    #         except Exception as e:
    #             result = {}
   #
   # #============图像=============
   #  def drawDetectBox(self,Img,Box_list):
   #      height = Img.shape[0]
   #      width = Img.shape[1]
   #      if len(Box_list) < 1:
   #          cv2.putText(Img, "OK", (int(width - width / 6),
   #                                  int(height / 6)), cv2.FONT_HERSHEY_PLAIN, 2.0,
   #                      (0, 255, 0), 2)
   #      else:
   #          for box in Box_list:
   #              x1 = box[0]
   #              y1 = box[1]
   #              x2 = box[2]
   #              y2 = box[3]
   #              conf = round(box[4], 3)
   #              cls = box[6]
   #              conf_cls = '%s %s' % (cls, conf)
   #              cv2.rectangle(Img, (x1, y1), (x2, y2), (255, 55, 55), thickness=2)
   #              cv2.putText(Img, conf_cls, (x1, y1),
   #                          cv2.FONT_HERSHEY_COMPLEX, 1.0, (0, 255, 0), thickness=2)
   #          cv2.putText(Img, "NG", (int(width - width / 6),
   #                                  int(height / 6)), cv2.FONT_HERSHEY_PLAIN, 5.0, (0, 0, 255), 2)
   #      return Img
   #  def paintCanvas(self):
   #      self.canvas.scale = 0.01 * self.zoomWidget.value()#
   #      # self.canvas.adjustSize()
   #      self.canvas.update()
   #
   #  def scaleFitWindow(self):
   #      a1 = self.w1 / self.h1
   #      w2 = self.canvas.pixmap.width() - 0.0
   #      h2 = self.canvas.pixmap.height() - 0.0
   #      a2 = w2 / h2
   #      return self.w1 / w2 if a2 >= a1 else self.h1 / h2
   #
   #  def adjustScale(self):
   #      value = self.scaleFitWindow()
   #      self.zoomWidget.setValue(int(100 * value))
   #
   #  def loadImg(self,qImg):
   #      pixmap = QPixmap.fromImage(qImg)
   #      self.canvas.loadPixmap(pixmap)
   #      self.adjustScale()
   #      self.paintCanvas()
   #  #---------------------------------------

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = TreeViewDemo()
    w.show()
    sys.exit(app.exec())
